package com.web_bloks.content.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Window;
import com.web_bloks.content.client.ContentPage;
import com.web_bloks.system.client.Logger;
import com.web_bloks.url.client.UrlFields;
import com.web_bloks.user.client.User;
import com.web_bloks.user.client.UserManager;

/**
 * The ContentManager:
 * -- uses the services of a PageManager to fetch the requested page
 * -- uses the services of a BasePage to display the fetched page
 * 
 * Make sure the configure fully the object through the CONFIGURATION API.
 * 
 * @author Jean-Lou Dupont
 * @deprecated
 */
@Deprecated
public class ContentManager {

	/**
	 * Status codes for displayPage 
	 */
	public enum Code {
		ok, loginRequired, adminRequired, pageNotFound
	}
	
	BasePage    base = null;
	PageManager pm   = null;
	UserManager um   = null;
	
	String titlePrefix = null;
	String loginNotice = null;
	
	String defaultPageName = null;
	
	/**
	 * Use GWT.create
	 */
	protected ContentManager() {	
	}
	
	/*****************************************
	 * CONFIGURATION API
	 *****************************************/
	public void setBasePage( BasePage b ) {
		base = b;
	}
	public void setPageManager(PageManager p) {
		pm = p;
	}
	public void setUserManager(UserManager u) {
		um = u;
	}
	public void setTitlePrefix(String tp) {
		titlePrefix = new String( tp );
	}
	public void setLoginNotice(String ln) {
		loginNotice = new String( ln );
	}
	public void setDefaultPage(String dpName) {
		defaultPageName = new String( dpName );
	}
	/*****************************************
	 * main API
	 *****************************************/
	
	public Code displayPage(UrlFields uf) {
		return displayPage( uf.page, uf.query );
	}
	
	public Code displayPage(String pageName, String params) {
	
		ContentPage p = pm.getContentPage(pageName);
		
		if (p == null)
			return Code.pageNotFound;
		
		Logger.logInfo(this.getClass()+".displayPage: name["+p.getPageName()+"]");
		
		if (p.requiresLogin()) {
			
			UserManager um = GWT.create(UserManager.class);
			User cUser = um.getCurrentUser();

			if ( null==cUser || !cUser.isLogin()) {
				navigateToDefault();
				return Code.loginRequired;
			}
		}
		
		// pass any query parameters
		p.setParams(params);
		
		//todo
		//base.setBody( p );
		setWindowTitle(p.getPageName());
		
		return Code.ok;
	}
	
	protected void navigateToDefault() {
		
		DeferredCommand.addCommand( new Command() {
			public void execute() {
				ContentPage p = pm.getContentPage(defaultPageName);
				//TODO
				//base.setBody(p);
				setWindowTitle(p.getPageName());
			}
		});
		
	}
	
	protected void setWindowTitle(String title ) {
		
		Window.setTitle( titlePrefix + " - " + title );		
	}
	
}//END